import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me: this,
      watchs: [],
      //模型
      models: {
        //模型

        laboratoryParams: {
          ...typeClassName["laboratoryParams"],
        },
        product: {
          ...typeClassName["product"],
        },
        equipment: {
          ...typeClassName["equipment"],
        },
      },
      equipOptions: [],
      productOptions: [],
      parentId: "",
      ids:[],
      dataSet: {
        //数据集
        treeData: [],
        currentData: {},
        formData: {
          sf_code: "",
          sf_name: "",
        },
        tableData: [],
        productTreeBindData: {},
        treeCurrentData: [],
        tableData: [],
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
    this.getReturnTrue();
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      console.log(comp, "comp");
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      // this.init();
      if (process.env.NODE_ENV === "development") {
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    init() {},
    loadPage(pageNavigation, filter) {
      
      let newFilter = {
        ...filter,
        className: this.models.laboratoryParams.className,
        type: this.models.laboratoryParams.type,
      };
      let hierFilter = this._$setFilteStr(newFilter, false);
      hierFilter = hierFilter + `&& id in (${this.ids})`;
      this._$queryByPage(
        this.models["laboratoryParams"].clzs,
        pageNavigation,
        hierFilter,
        "",
        "updateTime",
        false
      ).then((res) => {
        this.dataSet.tableData =
          this.models["laboratoryParams"].clzs.valueRecords;
      });
    },
    /**
     * 新增-弹窗显示
     */
    handleCreate() {
      if (this.dataSet.treeCurrentData.length > 0) {
        this.vms.createView.resetFields();
        this.dataSet.formData["productName"] =
        this.dataSet.treeCurrentData[0].data.sf_name;
      this.dataSet.formData["productCode"] =
          this.dataSet.treeCurrentData[0].data.id;
        this.dataSet.formData["equName"] = this.dataSet.treeCurrentData[0].data.equName;
        this.dataSet.formData["equCode"] = this.dataSet.treeCurrentData[0].data.equCode;
        this.dataSet.formData['imgNumber'] = this.dataSet.treeCurrentData[0].data.imgNumber
        this._modalShow("createModal");
      } else {
        this.$Message.info("请选择产品");
      }
    },
    /**
     * 查看-弹窗显示
     * @param {*} row
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.currentData = row;
      this.dataSet.formData = row.values;
    },
    /**
     * 编辑-弹窗显示
     * @param {*} row
     */
    handleEdit(row) {
      this._modalShow("editModal");
      row.values.maxParam = Number(row.values.maxParam);
      row.values.minParam = Number(row.values.minParam);
      this.dataSet.currentData = row;
      this.dataSet.formData = row.values;
    },
    /**
     * 删除单行
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      let _this = this;
      this._$deleteConfirm(() => {
        _this
          ._$deleteByIds(_this.models.laboratoryParams.clzs, [String(row.id)])
          .then((res) => {
            this.queryLaboratoryByProductId(this.dataSet.treeCurrentData[0].data);
          });
      });
    },
    handleDeleteMultiple(selection) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(row.id));
        _this
          ._$deleteByIds(_this.models.laboratoryParams.clzs, ids)
          .then((res) => {
            _this.vms.mainTable.navigation.page.pageNumber = 1;
            this.queryLaboratoryByProductId(this.dataSet.treeCurrentData[0].data);
          });
      });
    },
    // 新增确认
    createModalOk(btn) {
      this._$validateAll([this.vms.createView], (valid) => {
        btn.loading = false;
        if (valid) {
          // this.dataSet.formData["productName"] = this._$getOptionValue(
          //   this.productOptions,
          //   this.dataSet.formData.productCode
          // );
          // this.dataSet.formData["equName"] = this._$getOptionValue(
          //   this.equipOptions,
          //   this.dataSet.formData.equCode
          // );
          let formData = this.$modelObject.getTpl(
            this.models.laboratoryParams.modelType
          );
          formData.containerId =
            this.dataSet.productTreeBindData.hier.containerId;
          formData.className = this.models.laboratoryParams.className;
          formData.type = this.models.laboratoryParams.type;
          formData.name = +new Date();
          formData.values = this.dataSet.formData;
          this.$api.inspection.addLaboratoryParams(formData).then((flag) => {
            this._modalClose("createModal");
            this.queryLaboratoryByProductId(this.dataSet.treeCurrentData[0].data);
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
      btn.loading = false;
    },
    // 编辑确认
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        btn.loading = false;
        if (valid) {
          this.dataSet.formData["productName"] = this._$getOptionValue(
            this.productOptions,
            this.dataSet.formData.productCode
          );
          this.dataSet.formData["equName"] = this._$getOptionValue(
            this.equipOptions,
            this.dataSet.formData.equCode
          );
          this.dataSet.currentData.values = {
            ...this.dataSet.formData,
          };
          this.models.laboratoryParams.clz.setRecord(this.dataSet.currentData);
          this.models.laboratoryParams.clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              this.queryLaboratoryByProductId(this.dataSet.treeCurrentData[0].data);
            } else {
              this._modalClose("editModal");
            }
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
      btn.loading = false;
    },
    change(item, value) {},
    treeSelect(item, data) {
      console.log(item, data);
      this.dataSet.treeCurrentData = data;
      this.dataSet.tableData = [];
      if (data.length == 0) {
        return;
      }
      this.queryLaboratoryByProductId(item);
      // this.loadPage(this.vms.mainTable.navigation.page,{equipmentTypeCode:item.id})
    },
    queryLaboratoryByProductId(item) {
      this.$api.inspection.queryLaboratoryByProductId(item).then((res) => {
        this.dataSet.productTreeBindData = res;
        this.parentId = this._$getHierItemField(res.hier, "实验室参数", "nodeId");
        if (!this.parentId) {
          return;
        }
        let arr =
          this.dataSet.productTreeBindData.hier.content.filter(
            (item) => item.parentId == this.parentId
          ); // 进入页面点击设备存储所有的选项
          if (arr.length == 0) {
            this.dataSet.tableData = []
            this.vms.mainTable.navigation.page.total = 0
            return
        }
        this.ids = arr.map((item) => item.link.linkId).join(",");
        this.loadPage(this.vms.mainTable.navigation.page, {});
        // if (this.dataSet.tableData.length > 0) {
        //   this.dataSet.tableData = this.dataSet.tableData.map((item) => {
        //     return {
        //       ...item,
        //       values: {
        //         ...item.values,
        //       },
        //       ...item.values,
        //     };
        //   });
        // } else {
        //   this.dataSet.tableData = []
        //   this.vms.mainTable.navigation.page.total = 0;
        // }
      });
    },
    getReturnTrue() {
      Promise.all([this.getEquipOptions(), this.getProductOptions()]).then(
        (res) => {
          console.log(res);
          // this.result = res[0];
          // this.vms.mainTable.beforePageInit();
          this.vms.createView.beforePageInit();
          this.vms.editView.beforePageInit();
          this.vms.detailView.beforePageInit();
        }
      );
    },
    getEquipOptions() {
      let data = {
        className: this.models.equipment.className,
        type: this.models.equipment.type,
      };
      this.equipOptions = [];
      return this._$query(this.models.equipment.clzs, data).then((res) => {
        if (res) {
          this.models.equipment.clzs.records.forEach((item) => {
            this.equipOptions.push({
              label: item.values.sf_name,
              value: String(item.id),
            });
          });
          return true;
        } else {
          return false;
        }
      });
    },
    getProductOptions() {
      let data = {
        className: this.models.product.className,
        type: this.models.product.type,
      };
      this.productOptions = [];
      return this._$query(this.models.product.clzs, data).then((res) => {
        if (res) {
          this.models.product.clzs.records.forEach((item) => {
            this.productOptions.push({
              label: item.values.sf_name,
              value: String(item.id),
            });
            this.dataSet.treeData.push({
              id: item.id,
              parentId: "root",
              name: item.values.sf_name,
              sf_name: item.values.sf_name,
              sf_code: item.values.sf_code,
              equCode: item.values.equipId,
              equName: item.values.equipName,
              imgNumber: item.values.imgNumber
            });
          });
          return true;
        } else {
          return false;
        }
      });
    },
    uploadFile() {
      this.$refs.fileRef.dispatchEvent(new MouseEvent('click'));
    },
    fileChange(event){
      event.preventDefault();
      let formData = new FormData()
      let file = this.$refs.fileRef.files[0];
      let size = file.size;
      size = size/(1024*1024);
      if(size>5){//5M
          this.tools.errorPrompt('上传文件太大，请重新选择！');
          return;
      }
      formData.append('file',file)
      // formData.append("id",this.selRow.values.docsId);
      this.$api.inspection.impData(formData).then(resp => {
          this.tools.successPrompt('上传成功！');
      })
  },
  },
};
